package br.com.portalaberto.telas;

import java.util.*;
import java.io.*;

import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;

import br.com.portalaberto.PortalAbertoMIDlet;
import br.com.portalaberto.core.UIController;

public class FileChooser
{
	private String currDirName;
	private String pathCompleto;

	private Command view;
	private Command exit;

	private final static String UP_DIRECTORY = "..";
	private final static String MEGA_ROOT = "/";
	private final static String SEP_STR = "/";
	private final static char SEP = '/';

	private List browser;
	private Displayable algoDisplayable;
	
	private Imagem telaImagem;

	public Imagem getTelaImagem() {
		return telaImagem;
	}

	public List getBrowser() {
		return browser;
	}
	
	public Displayable getAlgoDisplayable() {
		return algoDisplayable;
	}

	private UIController controlador;

	private PortalAbertoMIDlet myMidlet;

	private static FileChooser fileChooser;

	public static FileChooser getInstance(UIController controlador){
		if(fileChooser == null){
			fileChooser = new FileChooser(controlador, true);
			return fileChooser;
		}else{
			return fileChooser;
		}
	}

	private FileChooser(UIController controlador, boolean suppressKeyEvents){

		currDirName = MEGA_ROOT;
		this.controlador = controlador;
		this.myMidlet = controlador.getPortalAbertoMIDlet();
		this.view = new Command("Abrir", Command.ITEM, 1);
		this.exit = new Command("Sair", Command.EXIT, 3);
	}

	public void exibeChooser(){//antiga startApp
		boolean isAPIAvailable = false;
		if (System.getProperty("microedition.io.file.FileConnection.version") != null){
			isAPIAvailable = true;
			System.out.println("hi");
			try{
				showCurrDir();
			}catch (SecurityException e){
				System.out.println(e);
			}catch (Exception e) {
				System.out.println(e);
			}
		}
		else{
			StringBuffer splashText = new StringBuffer
			(myMidlet.getAppProperty("MIDlet-Name")).append("\n").append(
					myMidlet.getAppProperty("MIDlet-Vendor")).
					append(isAPIAvailable?"":"\nFileConnection API not available");
			Alert splashScreen = new Alert(null,splashText.toString(),
					null,AlertType.INFO);
			splashScreen.setTimeout(3000);
			Display.getDisplay(myMidlet).setCurrent(splashScreen);
		}

	}

	public boolean threatCommandAction(Command c, Displayable d){
		if (c == view){
			List curr = (List)d;
			final String currFile = curr.getString(curr.getSelectedIndex());
			new Thread(new Runnable(){
				public void run(){
					if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)){
						traverseDirectory(currFile);
					}
					else{
						showFile(currFile);
					}
				}
			}).start();
			return false;
		}else if (c == exit){
			//retorna true e fecha a tela de acordo com o padrao
			return true;
		}else{
			return false;
		}
	}

	private void showCurrDir(){
		Enumeration e;
		FileConnection currDir = null;
		try{
			if (MEGA_ROOT.equals(currDirName)){
				e = FileSystemRegistry.listRoots();
				browser = new List(currDirName, List.IMPLICIT);
			}else{
				currDir = (FileConnection)Connector.open("file://localhost/" + currDirName);
				e = currDir.list();
				browser = new List( currDirName, List.IMPLICIT);
				browser.append(UP_DIRECTORY,null);
			}
			while (e.hasMoreElements()){
				String fileName = (String)e.nextElement();
				if (fileName.charAt(fileName.length()-1) == SEP){
					browser.append(fileName,null);
				}else{
					//Image image = Image.createImage(fileName);  
					//browser.append(fileName,null);  
					//Form form = new Form("Image here");                       
					//form.append(image);
					browser.append(fileName,null);
				}
			}
			browser.setSelectCommand(view);
			browser.addCommand(exit);
			browser.setCommandListener(controlador);
			if (currDir != null){
				currDir.close();
			}
			controlador.setCurrent(browser);
		}catch (IOException ioe){
			System.out.println(ioe);
		}
	}

	private void traverseDirectory(String fileName){
		if (currDirName.equals(MEGA_ROOT)){
			if (fileName.equals(UP_DIRECTORY)){
				// can not go up from MEGA_ROOT
				return;
			}
			currDirName = fileName;
		}else if (fileName.equals(UP_DIRECTORY)){

			int i = currDirName.lastIndexOf(SEP, currDirName.length()-2);
			if (i != -1){
				currDirName = currDirName.substring(0, i+1);
			}else{
				currDirName = MEGA_ROOT;
			}
		}else{
			currDirName = currDirName + fileName;
		}
		showCurrDir();
	}

	private void showFile(String fileName){
		InputStream fis = null;
		FileConnection fc = null;
		try	{
			fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
			pathCompleto = ("file://localhost/" + currDirName + fileName);
			if (!fc.exists()){
				throw new IOException("File does not exists");
			}
			fis = fc.openInputStream();
			//byte[] b = new byte[1024];
			//int length = fis.read(b, 0, 1024);
			
			String tipo = fileName.substring( (fileName.length()-3), fileName.length());
			tipo = tipo.toUpperCase();
			if( "PNG".equals(tipo) || "JPEG".equals(tipo) ||"JPG".equals(tipo) ||"GIF".equals(tipo) ||
					"BMP".equals(tipo)){
				Image image = Image.createImage(fis);
				telaImagem = Imagem.getInstance(controlador,image);
				controlador.setCurrent(telaImagem);
			}else{
				throw new Exception("File type bot supported");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				fis.close();
				fc.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public String getPathCompleto() {
		return pathCompleto;
	}

	public void setPathCompleto(String pathCompleto) {
		this.pathCompleto = pathCompleto;
	}
} 